<?php
namespace Home\Controller;
use Think\Controller;
	define("TOKEN", "ece44bfb7451c6c1abd33fabed0cc93d");
    define("APPID", "wx6d216db159fec225");
    define("APPSECRET", "b1faa3493802bf4175d41bb463454bb5");
class IndexController extends Controller {
    public function index(){
        $this->responseMsg();

    }
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $type=$postObj->MsgType;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>"; 
                if( $type=='event' && $postObj->Event=='subscribe')
                {
                    $msgType = "text";
                    $contentStr = "欢迎关注!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr; 
                }              
				if( $keyword=='呆逼')
                {
              		$msgType = "text";
                	$contentStr = "你猜!";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }
               
                $article=M('article')->where(array('keyword'=>$keyword))->select();
                if($article)
                {      
                    $textTpl="<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>%s</ArticleCount>
                        <Articles>";
                        foreach ($article as $a) {
                            $textTpl .="<item>
                            <Title><![CDATA[".$a['title']."]]></Title> 
                            <Description><![CDATA[".$a['description']."]]></Description>
                            <PicUrl><![CDATA[".$a['picurl']."]]></PicUrl>
                            <Url><![CDATA[".$a['url']."]]></Url>
                            </item>";
                        };
                        $textTpl .="</Articles>
                        </xml>";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,count($article));
                    echo $resultStr;
                }else{
                    $url="http://www.xiaodoubi.com/simsimiapi.php?msg=".$keyword;
                    $msgType = "text";
                    $contentStr =http_get($url);
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr; 

                }

        }else {
        	echo "";
        	exit;
        }
    }
    public function createMenu(){
        $access_token=getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
       /* $data=' {
             "button":[
             {  
                  "type":"click",
                  "name":"今日歌曲",
                  "key":"V1001_TODAY_MUSIC"
              },
              {
                   "name":"菜单",
                   "sub_button":[
                   {    
                       "type":"view",
                       "name":"搜索",
                       "url":"http://www.soso.com/"
                    },
                    {
                       "type":"view",
                       "name":"视频",
                       "url":"http://v.qq.com/"
                    },
                    {
                       "type":"click",
                       "name":"赞一下我们",
                       "key":"V1001_GOOD"
                    }]
               }]
         }';*/
         $data=array(
            'button'=>array(
                array(
                    "type"=>"click",
                    "name"=>"今日歌曲",
                    "key"=>"V1001_TODAY_MUSIC"
                    ),
                array(
                    'name'=>'菜单',
                    "sub_button"=>array(
                        array(
                            "type"=>"view",
                            "name"=>"搜索",
                            "url"=>"http://www.soso.com/"
                            ),
                        array(
                            "type"=>"view",
                            "name"=>"视频",
                            "url"=>"http://v.qq.com/"
                            ),
                        array(
                            "type"=>"click",
                            "name"=>"赞一下我们",
                            "key"=>"V1001_GOOD"
                            )
                        )
                    )
                )
            );
         $data=json_encode($data,JSON_UNESCAPED_UNICODE);
         var_dump($data);
         $s=http_post($url,$data);
         var_dump($s);
    }
   
		
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}